//
//  OpHeaderPageController.m
//  LoveFreshBeeReplica
//
//  Created by skywalker on 16/12/31.
//  Copyright © 2016年 斯芬克斯. All rights reserved.
//

#import "OpHeaderPageController.h"
#import "OpCycleView.h"
#import "HomeCellFlowLayout.h"
#import "OpHomeModel.h"
#import <MBProgressHUD.h>
#import "HomeViewCell.h"
#import "ButtonClickViewController.h"
#import "GuideView.h"
#define ImageCount  5
@interface OpHeaderPageController ()<UICollectionViewDataSource,UICollectionViewDelegate,HomeViewCellDelegate,CAAnimationDelegate>
@property (nonatomic, strong) NSArray* imageArray;
@property(nonatomic,strong)OpCycleView*cycleV;
@property(nonatomic,strong)UICollectionView *collectionView;
@property (strong, nonatomic) NSArray *arrData;
@property (strong, nonatomic) NSMutableDictionary *cellDict;
@property (nonatomic ,assign) NSInteger num;
//定义按钮记录
@property (nonatomic,strong) UIButton * selectedButton;

@end

@implementation OpHeaderPageController
- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadImageData];
    [self buildHotSell];
    [self loadHomeData];
}
-(void)buildHotSell{
    //设置热卖视图
    HomeCellFlowLayout *flowLayout = [[HomeCellFlowLayout alloc] init];
    UICollectionView *collertionVC = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
    self.collectionView = collertionVC;
    self.collectionView.backgroundColor=LRRandomColor;
    collertionVC.backgroundColor = [UIColor whiteColor];
    collertionVC.delegate = self;
    collertionVC.dataSource = self;
    [self.view addSubview:collertionVC];
    [collertionVC mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view);
        make.left.right.bottom.equalTo(self.view);
    }];
    //注册头部视图
    [collertionVC registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeadID"];
}
#pragma mark-头部视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if (kind == UICollectionElementKindSectionHeader) {
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"HeadID" forIndexPath:indexPath];
        //创建图片轮播器
        OpCycleView* cycleView = [[OpCycleView alloc]initWithFrame:CGRectZero];
        self.cycleV = cycleView;
        //传图片
        cycleView.imageArray = [self loadImageData];
        [headerView addSubview:cycleView];
        [cycleView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(headerView);
            make.height.offset(120);
        }];
        return headerView;
    }
    return nil;
}
#pragma mark-请求数据
-(NSArray*)loadImageData{
    NSMutableArray *arrM = [NSMutableArray arrayWithCapacity:ImageCount];
    for (NSInteger i = 0; i < ImageCount; i++) {
        NSString *imageName = [NSString stringWithFormat:@"%zd", i];
        // 加载图片
        UIImage *image = [UIImage imageNamed:imageName];
        // 保存到可变数组
        [arrM addObject:image];
    }
    return arrM;
}
- (void)loadHomeData {
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:hud];
    hud.label.text = @"正在加载";
    [hud showAnimated:YES];
    OpHomeModel *model = [[OpHomeModel alloc] init];
    NSString *urlstr = @"loveBeen/firstSell.json.php";
    NSDictionary *dict = [NSDictionary dictionaryWithObject:@"2" forKey:@"call"];
    [model loadDataWithHomeMethod:POST url:urlstr parameters:dict success:^(id responseobject) {
        self.arrData = responseobject;
        [self.collectionView reloadData];
        [hud removeFromSuperview];
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
//    [self build4button];
}
//设置边框
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 4, 0, 4);
}
#pragma mark -数据源方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.arrData.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSString *identifier = [_cellDict objectForKey:[NSString stringWithFormat:@"%@", indexPath]];
    if (identifier == nil) {
        identifier = [NSString stringWithFormat:@"%@", indexPath];
        
        [_cellDict setValue:identifier forKey:[NSString stringWithFormat:@"%@", indexPath]];
        
        [collectionView registerClass:[HomeViewCell class]  forCellWithReuseIdentifier:identifier];
        
    }
    HomeViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    OpHomeModel *model = self.arrData[indexPath.item];
    cell.model = model;
    cell.delegate = self;
    return cell;
}
#pragma mark-4个按钮
-(void)build4button{
    UIView * backview=[[UIView alloc]init];
    backview.backgroundColor=[UIColor blueColor];
    NSMutableArray * buttonArr=[NSMutableArray array];
    NSArray * titleArr=@[@"抽奖",@"秒杀",@"抢红包",@"蜂抱团"];
    NSArray * imgs=@[@"http://img01.bqstatic.com/upload/activity/activity_v4_20206_1452163603_icon.jpg",@"http://img01.bqstatic.com/upload/activity/activity_v4_20333_1451871780_icon.jpg",@"http://img01.bqstatic.com/upload/activity/activity_v4_20596_1452250014_icon.jpg",@"http://img01.bqstatic.com/upload/activity/activity_v4_20382_1451896099_icon.jpg"];
    UIButton * btn=[UIButton buttonWithType:UIButtonTypeCustom];
    for (int i=0; i<titleArr.count; i++) {
        btn.tag=i;
        [btn setTitleColor:[UIColor blackColor] forState: UIControlStateNormal ];
        [btn setTitle:titleArr[i] forState:  UIControlStateNormal];
        [btn  addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
        btn.titleLabel.font=[UIFont systemFontOfSize:16];
        [btn sd_setImageWithURL:imgs[i] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"v2_placeholder_square"]];
       [backview addSubview:btn];
    }
    [buttonArr addObject:btn];
    //布局
    [buttonArr mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:0 leadSpacing:0 tailSpacing:0];
    [buttonArr mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(backview);
    }];
    [backview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.cycleV);
        make.height.equalTo(self.view).offset(40);
        make.width.equalTo(self.view).offset(kScreenWidth);
    }];
}
-(void)clickButton:(UIButton *)button{
    ButtonClickViewController * btvc=[[ButtonClickViewController alloc]init];
    [self.navigationController pushViewController:btvc animated:YES];
}
//实现代理方法
- (void)HomeViewCell:(HomeViewCell *)HomeViewCell withImageView:(UIImageView *)modelImg{
    //转化坐标
    //    NSLog(@"%@",modelImg);
    CGPoint startP = [HomeViewCell convertPoint:modelImg.center toView:self.view.window];
    //创建图画
    UIImageView *imageView = [[UIImageView alloc] initWithImage:modelImg.image];
    imageView.frame = modelImg.bounds;
    imageView.center = startP;
    [self.view.window addSubview:imageView];
    //定义结束点
    CGPoint endP = CGPointMake(self.view.bounds.size.width * 0.61, self.view.bounds.size.height);
    CAAnimationGroup *groupAni = [CAAnimationGroup animation];
    //抛物线
    CAKeyframeAnimation *keyAni = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    //    缩放
    CABasicAnimation *scaleAni = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    scaleAni.toValue = @(0.1);
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:startP];
    //抛物线
    [path addQuadCurveToPoint:endP controlPoint:CGPointMake(startP.x + 50, startP.y - 50)];
    keyAni.path = path.CGPath;
    //    keyAni.duration = 1;
    keyAni.fillMode = kCAFillModeForwards;
    keyAni.removedOnCompletion = NO;
    
    groupAni.delegate = self;
    
    //setValueForkey !!!!!注意:要在添加动画之前做这件事儿
    
    groupAni.animations = @[keyAni,scaleAni];
    groupAni.duration = 1;
    [groupAni setValue:imageView forKey:@"name"];
    
    groupAni.fillMode = kCAFillModeForwards;
    groupAni.removedOnCompletion = NO;
    
    [imageView.layer addAnimation:groupAni forKey:nil];
    
    
}
- (void)HomeViewCell:(HomeViewCell *)HomeViewCell withButton:(UIButton *)minusSignBtn{
    
    self.num--;
    
    if (self.num > 9)
    {
        [[[[[self tabBarController]viewControllers] objectAtIndex:2]tabBarItem]setBadgeValue:[NSString stringWithFormat:@"%@",@"9+"]];
        //        Num = [NSString stringWithFormat:@"9+"];
    }
    else
    {
        [[[[[self tabBarController]viewControllers] objectAtIndex:2]tabBarItem]setBadgeValue:[NSString stringWithFormat:@"%zd",self.num]];
        
        
    }
    if (self.num == 0) {
        
        [self.tabBarController.tabBar.items objectAtIndex:2].badgeValue = nil;
        
    }
}
@end
